<template>
  <div class="stats-container">
    <div class="stats-station-head" v-if="type === 'event_type'">
      <div class="stats-station-card">
        <p>{{$t('report.stationView.title1')}}</p>
        <h3>{{unfinishedCus | convertZero}}</h3>
        <div class="stats-station-card-bottom">{{$t('report.stationView.title2')}}：{{yesterdayCus | convertZero}}</div>
      </div>

      <div class="stats-station-card">
        <p>{{$t('event.components.eventEditForm.text2')}}</p>
        <h3><a href="#" @click.prevent="openDetail('/event', 'unfinishedEvent')">{{unfinishedEvent | convertZero}}</a></h3>
        <div class="stats-station-card-bottom">{{$t('report.stationView.title4')}}：{{processingEvent | convertZero}}</div>
      </div>

      <div class="stats-station-card">
        <p>{{$t('report.stationView.title3')}}</p>
        <h3><a href="#" @click.prevent="openDetail('/event', 'todayFinish')">{{todayFinish | convertZero}}</a></h3>
        <div class="stats-station-card-bottom">{{$t('report.stationView.title5')}}：{{yesterdayFinish | convertZero}}</div>
      </div>

      <div class="stats-station-card">
        <p>{{$t('report.stationView.title8')}}</p>
        <h3>{{the30daysGood | toPercent}}</h3>
        <div class="stats-station-card-bottom">{{$t('report.stationView.title9')}}：{{the30daysBad | toPercent}}</div>
      </div>

    </div>

    <div class="stats-row" ref="eventCountChart" v-if="type === 'event_type'">
      <div class="stats-panel">
        <div class="stats-panel-head stats-form">
          <h3>{{$t('report.stationView.title10')}}
          </h3>
          <div class="stats-form-group">
            <!-- <div id="date-range" class="stats-form-daterange">
              <span>{{timeStart}} - {{timeEnd}}</span> 
              <b class="caret"></b>
            </div> -->
            <date-picker @datePicker="datePicker" />
          </div>
        </div>
        <div class="stats-panel-body">
          <div style="text-align:center;">
            <div class="stats-btn-group">
              <button type="button" :class="{'stats-checked': chart == 'event-type-chart'}" 
                      @click="chooseChart('event-type-chart')">{{$t('common.label.eventType')}}</button>
              <button type="button" :class="{'stats-checked': chart == 'event-score-chart'}" 
                      @click="chooseChart('event-score-chart')">{{$t('report.stationView.title11')}}</button>
              <button type="button" :class="{'stats-checked': chart == 'event-product-chart'}" 
                      @click="chooseChart('event-product-chart')">{{$t('common.base.column.productType')}}</button>
          
            </div>
          </div>
          <keep-alive>
            <component
              :is="chart"
              :chart-data="pieData"
              :time-start="timeStart"
              :chart-type="type"
              :export-track="exportTrack"
              @imageDownload="imageDownload"
              :time-end="timeEnd">
            </component>
          </keep-alive>
        </div>
      </div>
    </div>

    <div class="stats-row" v-if="type === 'undone_event'">
      <station-table @trackEvent="stTrackEventHandler" :chart-type="type" :export-track="exportTrack"></station-table>
    </div> 
    
    <div v-if="type === 'personnel-event'"> 
      <staff-event-table :chart-type="type"></staff-event-table>
      <staff-category-chart :evaluate-config="evaluateConfig" :chart-type="type"></staff-category-chart>
    </div>

  </div>
</template>

<script>
import _ from 'lodash';
import qs from 'src/util/querystring';
import { formatDate } from 'pub-bbx-utils';
import EventTypeChart from './EventTypeChart.vue';
import EventProductChart from './EventProductChart.vue';
import EventScoreChart from './EventScoreChart.vue'
import StationTable from './StationTable.vue'
import StaffCategoryChart from './StaffCategoryChart.vue';
import StaffEventTable from './StaffEventTable.vue';
import { safeNewDate } from '@src/util/time';

export default {
  name: 'station-view',
  data(){
    return {
      // 未完成事件
      unfinishedEvent: '--',
      // 今日完成事件
      todayFinish: '--',
      // 昨日完成事件
      yesterdayFinish: '--',
      // 近30天好评率
      the30daysGood: '--',
      // 未完成订单
      unfinishedOrder: '--',
      // 近30天订单
      the30daysOrder: '--',
      // 接入客户
      unfinishedCus: '--',
      // 昨日服务客户
      yesterdayCus: '--',
      // 进行中事件
      processingEvent: '--',
      // 近30天差评率
      the30daysBad: '--',
      loading: true,

      pieData: {},
      timeStart: '',
      timeEnd: '',
      teamId: '',
      chart: 'event-type-chart',
      evaluateConfig: {},
      type: '', // 判断是从哪里进来的
    }
  },
  methods: {
    exportTrack(isExportAll, hasTab = true) {
      let tab
      if(hasTab) tab = this.chart.toLocaleUpperCase().replaceAll('-', '_');
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.type,
        tab
      }, '*')
    },
    imageDownload() {
      this.type && this.$track.commonFn.chartTrack(this.type, 'DOWNLOAD_REPORT_IMAGE', this.$track)
    },
    chooseChart(chart){
      this.chart = chart;
    },
    openDetail(url, to){
      let fromId = window.frameElement.getAttribute('id');

      let model = {};

      if(to == 'unfinishedEvent'){
        model.state = 'created';
      }

      if(to == 'todayFinish'){
        model.state = 'finished'
        // 2018/05/02 - 2018/05/02
        let today = formatDate(safeNewDate(), 'yyyy/MM/dd');
        model.completeTime = `${today } - ${ today}`;
      }

      if(to == 'unfinishedOrder'){
        model.state = 'created';
      }

      this.$platform.openTab({
        id: 'M_CASE_LIST', 
        title: this.$t('common.base.serviceEvent'), 
        close: true, 
        url: `${url }?${ qs.stringify(model)}`,
        fromId
      });
      
      
    },
    async initStationHead(){
      try {
        let data = await this.fetchStationCountData();
        
        this.unfinishedEvent = data.unfinishedEvent;
        this.todayFinish = data.todayFinish;
        this.yesterdayFinish = data.yesterdayFinish;
        this.the30daysGood = data['30daysGood'];
        this.unfinishedOrder = data.unfinishedOrder;
        this.the30daysOrder = data['30daysOrder'];
        this.unfinishedCus = data.unfinishedCus;
        this.yesterdayCus = data.yesterdayCus;
        this.processingEvent = data.processingEvent;
        this.the30daysBad = data['30daysBad'];
      } catch (error) {
        console.log(error)
      }
    },
    fetchStationCountData(){
      return this.$http.get('/api/report/outside/stats/station/count', {});
    },
    // station-chart trackEventHandler TalkingData事件埋点
    scTrackEventHandler(type) {
      switch (type) {
      case 'chooseDate':
        this.$tdOnEvent('pc：服务台报表-日期选择事件');
        break;
      default:
        break;
      }
    },
    // station-table trackEventHandler TalkingData事件埋点
    stTrackEventHandler(type) {
      switch (type) {
      case 'updateServerName':
        this.$tdOnEvent('pc：服务台报表-服务人员输入框事件');
        break;
      case 'selectColumn':
        this.$tdOnEvent('pc：服务台报表-选择列事件');
        break;
      case 'expand':
        this.$tdOnEvent('pc：服务台报表-展开数据事件');
        break;
      default:
        break;
      }
    },
    initPie(start, end){

      this.timeStart = start;
      this.timeEnd = end;

      this.renderPie();
    },
    chooseDate(start, end){
      this.timeStart = start;
      this.timeEnd = end;
      this.renderPie();
    },
    async renderPie(){
      try {
        let instance = this.$loading.show(this.$refs.eventCountChart);
        let pieData = await this.fetchEvenCount();
        instance.hide();
        this.pieData = _.assign({}, this.pieData, pieData.data);
        
      } catch (error) {
        console.log(error)
      }
    },
    fetchEvenCount(){
      let params = {
        timeStart: this.timeStart,
        timeEnd: this.timeEnd
      };
      return this.$http.post('/api/report/outside/stats/station/eventCount', params);
    },
    datePicker(data) {
      // 初始化趋势图
      this.initPie(data[0], data[1]);
      this.type && this.$track.commonFn.chartTrack(this.type, 'REPORT_SEARCH_TIME', this.$track)
    }
  },
  mounted(){
    this.type = window.location.href.split('type=')[1]
    let initData = JSON.parse(sessionStorage.getItem('_init_data'))
    this.evaluateConfig = initData.evaluateConfig || {};
    
    if (this.type === 'event_type') this.initStationHead();
  },
  components: {
    [EventTypeChart.name]: EventTypeChart,
    [EventProductChart.name]: EventProductChart,
    [EventScoreChart.name]: EventScoreChart,
    [StationTable.name]: StationTable,
    [StaffCategoryChart.name]: StaffCategoryChart,
    [StaffEventTable.name]: StaffEventTable
  }
}
</script>

<style lang="scss">
.stats-station-head{
  display: flex;
  flex-flow: row nowrap;
  padding: 5px 7.5px;
  justify-content: flex-end;
}

.stats-task-head{
  display: flex;
  flex-flow: row nowrap;
  padding: 5px 7.5px;
  justify-content: flex-end;
}

.stats-station-card{
  flex: 1;
  margin-left: 15px;

  border-radius: 2px;
  background-color: #fff;
  text-align: center;

  p{
    padding: 15px 0 8px;
    margin: 0;
    font-size: 14px;
  }

  h3{
    font-weight: 400;
    font-size: 24px;
    line-height: 34px;
    margin: 0;
    padding: 5px 0;

    a{
      color: #2d9cf5;
    }
  }

  &:first-child{
    margin-left: 0;
  }
  
  .stats-station-card-bottom {
    margin-bottom: 15px;
  }
}

.stats-task-table-header{
  display: flex;
  flex-flow: row nowrap;
  padding: 5px;

  h3{
    font-size: 14px;
    flex: 1;
    margin: 0;
    line-height: 30px;
  }

  button{
    margin-left: 5px;
  }
}

#event-product-chart,
#event-type-chart,
#event-score-chart{
  height: 520px;
}
</style>
